import config from './config.js';
import md5 from 'js-md5';

const begincommin = (controller, method, query) => {
	return new Promise((resolve, reject) => {
		// 获取时间
		let timestamp = (Date.parse(new Date())) / 1000;
		if ("" == query || null == query) {
			query = {};
		}
		
		let url
		if (query.root) {
			url = config.baseUrl + controller
		} else {
			url = config.global_baseddConnUrl + controller
		}
		
		if (query.root) {
			delete query.root 
		}

		/**
		 * 生成签名
		 * @param {Object} query  
		 */
		CalcuMD5(query).then(res => {
			//参数
			// let parameter = JSON.stringify(query);
			// if (config.global_isTest) {
			// 	console.log(parameter, config.global_baseddConnUrl + controller);
			// }
			uni.request({
				url, //仅为示例，并非真实接口地址。
				method,
				data: query,
				header: {
					'content-type': 'application/x-www-form-urlencoded;charset=UTF-8', //自定义请求头信息
					'X-Requested-With': 'XMLHttpRequest',
					'sign': res,
					'time': timestamp,
					'token': uni.getStorageSync('yw_token') || '',
					'version': config.global_version,
					'plat': uni.getStorageSync('yw_platform'),
				},
				success: (data) => {
					//定义变量
					let jsondata = data;
					// 打印
					if (config.global_isTest) {
						console.log(jsondata);
					}
					// 服务器报错
					if (jsondata.statusCode == 404) {
						uni.showToast({
							title: jsondata.statusCode,
							duration: 2000,
							icon: 'none'
						});
						reject(jsondata.statusCode);
						return
					}
					// 接口报错
					if (jsondata.data.code == 200) {
						resolve(jsondata.data)
					} else if (jsondata.data.code == 1005) {
						uni.showToast({
							title: '通讯失败了~',
							duration: 2000,
							icon: 'none'
						});
						reject(jsondata.statusCode);
					} else if (jsondata.data.code == 2001) {
						uni.showToast({
							title: jsondata.data.msg,
							duration: 2000,
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/common/login/login'
							})
						}, 1500)
						reject(jsondata.statusCode);
					} else if (jsondata.data.code == 2002) {
						uni.showToast({
							title: jsondata.data.msg,
							duration: 2000,
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/mine/personal-data/personal-data'
							})
						}, 1500)
						reject(jsondata.statusCode);
					} else {
						uni.showToast({
							title: jsondata.data.msg,
							duration: 2000,
							icon: 'none'
						});
						reject(jsondata.data);
					}
				},
				fail: (err) => {
					console.log(`失败原因:`, err);
					reject(err);
				},
				complete() {
					// uni.hideLoading();
				}
			})
		});
	})
}
const request = ({
	controller,
	method,
	query
}) => {
	return new Promise((resolve, reject) => {
		// uni.showLoading({
		//     title: '',
		// 	mask: true
		// });
		let palt = uni.getStorageSync('yw_platform');
		let imei = uni.getStorageSync('appimei'); //手机IMEI
		if (null == palt || "" == palt || null == imei || "" == imei) {
			//获取手机的信息
			uni.getSystemInfo({
				success: function(res) {
					if ('ios' == res.platform) {
						uni.setStorageSync('yw_platform', '1');
					} else if ('android' == res.platform) {
						uni.setStorageSync('yw_platform', '2');
					} else {
						uni.setStorageSync('yw_platform', '2');
					}
					//  设置IMEI 
					// uni.setStorageSync('appimei', '1234567890');


					// 开始通信
					begincommin(controller, method, query).then(res => {
						resolve(res)
					}).catch(err => {
						reject(err);
					});
					// return returnback(res)
				},
			})
		} else {
			// 开始通信
			begincommin(controller, method, query).then(res => {
				resolve(res)
			}).catch(err => {
				reject(err);
			});
		}
	}).then(res => {
		return [null, res]
	}).catch(err => [err])
}

/**
 * 作者： TKE
 * 时间： 2019/12/17 0017
 * 功能：md5加密请求体
 * 描述：
 */
function CalcuMD5(obj) {
	// console.log(JSON.stringify(obj));
	return new Promise(resolve => {
		const key = config.global_aeskey;
		let sign = ''
		if (JSON.stringify(obj) === '{}') {
			sign = key + '--' + key
		} else {
			Object.keys(obj).sort().forEach((k) => {
				if (Object.prototype.toString.call(obj[k]) === '[object Number]') {
					obj[k] = obj[k].toString()
				}
				sign += key + k + '--' + md5(JSON.stringify(obj[k])) + key
			})
		}
		// console.log(sign);
		resolve(md5(sign).toUpperCase());
	})
}


export default request
